package org.example.ams.controller.system;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.example.common.api.CommonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileUpDownController {

    @Value("${file.cache.directory}")
    private String cacheDirectory = "C:/ams/cache";

    @PostMapping("/upload")
    public CommonResult fileUpload(HttpServletRequest request,MultipartFile file) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 判断是否分片
        if (parameterMap.get("is_chunk") == null) {
            // 不分片
            // TODO 不分片的时候，直接上传到文件服务器
        } else {
            // 判断是分片上传请求还是合并请求
            String[] types = parameterMap.get("type");
            if (types == null) {
                return CommonResult.failed("请求参数错误");
            } else if ("0".equals(types[0])) {
                // 分片上传请求
                String[] tmp1 = parameterMap.get("chunk_index");
                String[] tmp2 = parameterMap.get("file_uid");
                String[] tmp3 = parameterMap.get("file_name");
                if (tmp1 == null || tmp2 == null || tmp3 == null) {
                    return CommonResult.failed("请求参数错误");
                }
                Integer index = Integer.parseInt(tmp1[0]);
                String fileUID = tmp2[0];
                String fileName = tmp3[0];
                if (fileName.contains(".")) {
                    fileName = fileName.substring(0,fileName.lastIndexOf("."));
                }
                // 分片文件名
                String tmpFileName = index + "_" + fileName;
                // 分片文件存放路径 cachePath + fileUID + 分片文件名
                String path = cacheDirectory + File.separator + fileName + File.separator + tmpFileName;
                File tempFIle = new File(path);
                try {
                    // 断点续传
                    if (!tempFIle.exists()) {
                        FileUtils.writeByteArrayToFile(tempFIle, file.getBytes());
                    }
                } catch(IOException e){
                    return CommonResult.failed();
                }
            } else {
                // 合并请求
                String[] tmp4 = parameterMap.get("chunk_count");
                String[] tmp2 = parameterMap.get("file_uid");
                String[] tmp3 = parameterMap.get("file_name");
                if (tmp2 == null || tmp3 == null || tmp4 == null) {
                    return CommonResult.failed("请求参数错误");
                }
                String fileUID = tmp2[0];
                String fileName = tmp3[0];
                String dir = null;
                if (fileName.contains(".")) {
                    dir = fileName.substring(0,fileName.lastIndexOf("."));
                } else {
                    dir = fileName;
                }
                Integer chunks = Integer.parseInt(tmp4[0]);
                String completeFilePath = cacheDirectory + File.separator + dir + File.separator + fileName;
                File completeFile = new File(completeFilePath);
                if (completeFile.exists()) {

                    return CommonResult.success(null,null);
                }
                String path = null;
                File chunkFile = null;
                FileInputStream fileInputStream = null;
                BufferedInputStream in = null;
                byte[] cache = new byte[1024];
                for(int i = 0; i < chunks; i++) {
                    try {
                        path = cacheDirectory + File.separator + dir + File.separator + i + "_" + dir;
                        chunkFile = new File(path);
                        fileInputStream = new FileInputStream(chunkFile);
                        in = new BufferedInputStream(fileInputStream);
                        while(in.read(cache) > 0) {
                            FileUtils.writeByteArrayToFile(completeFile,cache,true);
                        }
                    } catch (IOException e) {
                        return CommonResult.failed();
                    } finally {
                        try {
                            if (in != null) {
                                in.close();
                            }
                            if (fileInputStream != null) {
                                fileInputStream.close();
                            }
                            // 删除分片文件
                            boolean flag = chunkFile.delete();
                            System.out.println("");
                        }catch (Exception e) {
                            log.error("文件流关闭异常！");
                            return CommonResult.success(null);
                        }
                    }
                }
            }
        }
        return CommonResult.success(null,null);
    }
}
